package com.duke.shaking.profile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;

import com.duke.shaking.R;
import com.duke.shaking.TitleActivity;
import com.duke.shaking.net.AsyncHttpResponseWithResultHandler;
import com.duke.shaking.net.NetUtils;

public class HobbiesEditActivity extends TitleActivity
			implements CompoundButton.OnCheckedChangeListener, View.OnTouchListener {
	
	private ArrayList<Integer> hobbies;
	private String hobbiesName;
	private int checkedNum = 0;
	private static final int MAX_NUM = 4;
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent i = getIntent();
        ArrayList<Integer> hobbies = (ArrayList<Integer>)i.getSerializableExtra("hobbies");
        if (hobbies != null) {
        	initCheckBoxes(hobbies);
        }
	}
	
	public boolean isSelectedHobby(int hobby, ArrayList<Integer> hobbies) {
		if (hobbies == null) {
			return false;
		}
		
		for (int i = 0; i < hobbies.size(); i ++) {
			int h = (Integer)hobbies.get(i);
			if (h == hobby) {
				return true;
			}
		}
		return false;
	}
	
	private void initCheckBoxes(ArrayList<Integer> hobbies) {
		ViewGroup checkboxes = (ViewGroup) findViewById(R.id.group_checkboxes);
		for (int i = 0; i < checkboxes.getChildCount(); i++) {
			View child = checkboxes.getChildAt(i);
			if (child instanceof CheckBox) {
				try {
					String tag = (String)child.getTag();
					int hobby = 0;
					hobby = Integer.parseInt(tag);
					if (isSelectedHobby(hobby, hobbies)) {
						((CheckBox)child).setChecked(true);
						checkedNum ++;
					}
					((CheckBox)child).setOnCheckedChangeListener(this);
					((CheckBox)child).setOnTouchListener(this);
				}
				catch(Exception ex) {
				}
			}
		}
		
		if(checkedNum >= MAX_NUM) {
			enableCheckBoxes(false);
		}
    }
	
	private String getHobbies(ArrayList<Integer> hobbies) {
		ViewGroup checkboxes = (ViewGroup) findViewById(R.id.group_checkboxes);
		String hobbiesName = "";
		for (int i = 0; i < checkboxes.getChildCount(); i++) {
			View child = checkboxes.getChildAt(i);
			if (child instanceof CheckBox
				&& ((CheckBox)child).isChecked()) {
				try {
					String tag = (String)child.getTag();
					int hobby = Integer.parseInt(tag);
					String hobbyName = ((CheckBox)child).getText().toString();
					hobbies.add(hobby);
					if (!hobbiesName.equals("")) {
						hobbiesName += " ";
					}
					hobbiesName += hobbyName;
				}
				catch(Exception ex) {
				}
			}
		}
		return hobbiesName;
	}
	
	@Override
	protected int getLayoutId() {
		// TODO Auto-generated method stub
		return R.layout.activity_hobbies_edit;
	}

	@Override
	protected void onTitleInit() {
		// TODO Auto-generated method stub
		initTitle(TITLE_BTN_EXIST | TITLE_BTN_BACK,
				R.string.back,
				TITLE_BTN_EXIST,
				R.string.save,
				R.string.hobbies);
	}

	public void onLeftBtn(View v) {
		Intent intent = new Intent();  
        setResult(RESULT_CANCELED, intent); 
        finish(); 
	}
	
	public void onRightBtn(View v) {
		AsyncHttpResponseWithResultHandler responseHandler = new AsyncHttpResponseWithResultHandler(){
			
        	@Override
			public void onResultSuccess(String response) {
				// TODO Auto-generated method stub
				super.onResultSuccess(response);
				
				afterSaveSuccess();
			}

			@Override
			public void onResultFailure(String result) {
				// TODO Auto-generated method stub
				super.onResultFailure(result);
				
				toast("保存失败");
			}
        };
        
        hobbies = new ArrayList<Integer>();
        hobbiesName = getHobbies(hobbies);
        Map<String, String> params = new HashMap<String, String>();
        params.put(NetUtils.TOKEN, me.getAuthToken());
        NetUtils.updateProfile(this, responseHandler, params, hobbies);
	}
	
	private void afterSaveSuccess() {
		Intent intent = new Intent(); 
        intent.putExtra("hobbies", hobbies);
        me.setHobbies(hobbies);
        intent.putExtra("hobbiesName", hobbiesName);
		setResult(RESULT_OK, intent); 
        finish(); 
	}
	
	public void onCheckedChanged(CompoundButton checkBox, boolean checked) {
		Log.i(TAG, "onCheckedChanged");
		if(checked) {
			checkedNum ++;
		} else {
			checkedNum --;
		}

		if(checkedNum >= MAX_NUM) {
			enableCheckBoxes(false);
		} else {
			enableCheckBoxes(true);
		}
	}
	
	public boolean onTouch(View v, MotionEvent event) {
		if(checkedNum >= MAX_NUM) {
			CheckBox checkBox = (CheckBox)v;
			if(!checkBox.isChecked()) {
				toast("最多只能选四个兴趣爱好");
			}
		}
		
		// TODO Auto-generated method stub
		return false;
	}

	private void enableCheckBoxes(boolean clickable) {
		ViewGroup checkboxes = (ViewGroup) findViewById(R.id.group_checkboxes);
		for (int i = 0; i < checkboxes.getChildCount(); i++) {
			View child = checkboxes.getChildAt(i);
			if (child instanceof CheckBox) {
				CheckBox checkBox = (CheckBox)child;
				if(!clickable) {
					// only make non-checked checkbox to unclickable
					if(!checkBox.isChecked()) {
						checkBox.setClickable(clickable);
					}
				} else {
					checkBox.setClickable(clickable);
				}
			}
		}
	}

}
